package com.springboot.module.user.controller.fileUpload;

import com.springboot.module.user.utils.aliyun.AliyunOSSOperator;
import com.springboot.module.user.utils.result.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;


@RestController
@Slf4j
@RequestMapping("/file")
public class uploadController {
    /**
     * 上传文件 - 参数名file
     */
  /*  @PostMapping("/upload")
    public ApiResult upload(MultipartFile file) throws Exception {
        log.info("上传文件: {}", file);
        if (!file.isEmpty()) {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString().replace("-", "") + extName;
            LocalDate localDate = new LocalDate();
            // 拼接完整的文件路径
            File targetFile = new File(localDate + "-" + uniqueFileName);
            createFileSafely(String.valueOf(targetFile));
            // 保存文件
            file.transferTo(targetFile);
        }
        return ApiResult.success();
    }
    public void createFileSafely(String filePath) {
        try {
            // 构造Path对象
            Path path = Paths.get(filePath);

            // 确保父目录存在
            Path parentDir = path.getParent();
            if (parentDir != null) {
                Files.createDirectories(parentDir);
            }

            // 创建文件（如果不存在）
            if (!Files.exists(path)) {
                Files.createFile(path);
            }

            System.out.println("文件创建成功：" + path);
        } catch (IOException e) {
            System.err.println("文件操作失败：" + e.getMessage());
            e.printStackTrace();
        }
    }*/

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    @PostMapping("/upload")
    public ApiResult upload(MultipartFile file) throws Exception {
        log.info("上传文件：{}", file);
        if (!file.isEmpty()) {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString().replace("-", "") + extName;
            // 上传文件
            String url = aliyunOSSOperator.upload(file.getBytes(), uniqueFileName);
            return ApiResult.success(url);
        }
        return ApiResult.failure("上传失败");
    }

}
